package com.inheritance.controller;

import com.inheritance.common.Result;
import com.inheritance.entity.User;
import com.inheritance.service.UserService;
import com.inheritance.utils.JwtUtil;
import com.inheritance.utils.Md5Util;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dyn
 * @since 2024-12-26
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;


    // 注册
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        User info = userService.info(user);
        if (info != null) {
            // 用户已存在，返回错误
            return Result.error("用户已存在");
        } else {
            int insert = userService.register(user);
            if (insert > 0) {
                return Result.success("注册成功");
            } else {
                return Result.error("注册失败，请稍后再试");
            }
        }
    }


    // 登录
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        User info = userService.info(user);
        if (info == null) {
            return Result.error("用户不存在");
        } else {
            String password = Md5Util.getMD5String(user.getPassword());
            if (!password.equals(info.getPassword())) {
                return Result.error("密码错误");
            }
            if (!info.getStatus().equals(1)) {
                return Result.error("账号被禁用");
            }
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", info.getId());
            String token = JwtUtil.getToken(claims);
            return Result.success("登录成功", token);
        }
    }

    // 获取用户信息
    @GetMapping("/info")
    public Result<?> getUserInfo() {
        User user = userService.userInfo();
        if (user != null) {
            return Result.success("查询成功", user);
        } else {
            return Result.error("获取用户信息失败");
        }
    }

    //获取用户列表
    @GetMapping("/list")
    public Result<?> getUserList(@Param("username") String username) {
        return Result.success("查询成功", userService.list(username));
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable String id) {
        int i = userService.delete(id);
        if (i > 0) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    // 修改用户信息
    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        int i = userService.update(user);
        if (i > 0) {
            return Result.success("修改成功");
        } else {
            return Result.success("修改失败");
        }
    }
}
